<?php

namespace common\models;

use Yii;
use yii\base\Model;

class Word extends Model{

    /**
     * 抓取有道数据并入库，如果单词存在则更新
     * @param $word
     * @return string
     */
    public static function synYoudao($word){
        $synData = Youdao::getInfo($word);
        //echo '<pre>'; print_r($synData);

        $trans_arr = isset($synData["trans"]) ? $synData["trans"] : [];
        $trans_str = implode("|", $trans_arr);

        if(!isset($synData["word"]) || empty($synData["word"])){
            throw new \RuntimeException("抓取失败", -1);
        }

        $data = [
            'word' => isset($synData["word"]) ? $synData["word"] : "",
            'ipa_en' => isset($synData["ipa"][0]) ? addslashes($synData["ipa"][0]) : '',
            'ipa_us' => isset($synData["ipa"][1]) ? addslashes($synData["ipa"][1]) : '',
            'trans' => $trans_str,
            'update_time' => time(),
        ];
        //print_r($data);

        $db = Yii::$app->db;
        //注意，这里要用抓取到的单词作为WHERE条件，因为有大小写问题
        $id = intval($db->createCommand("SELECT `id` FROM {{%english}} WHERE BINARY word='".$data["word"]."'")->queryScalar());
        if($id > 0){
            $line = $db->createCommand()->update('{{%english}}', $data, 'id='.$id)->execute();
            if($line == 1){
                return $id;
            }else{
                throw new \RuntimeException("单词已存在，编辑更新失败!", -2);
            }
        }else{
            $line = $db->createCommand()->insert('{{%english}}', $data)->execute();
            if($line == 1){
                $id = $db->getLastInsertID();
                return $id;
            }else{
                throw new \RuntimeException("单词添加失败!", -3);
            }
        }
    }

    public static function fixFromYoudao($word){
        $synData = Youdao::getInfo($word);
        echo '<pre>';
        print_r($synData);

        $trans_arr = isset($synData["trans"]) ? $synData["trans"] : [];
        $trans_str = implode("|", $trans_arr);

        $data = [
            'word' => isset($synData["word"]) ? $synData["word"] : "",
            'ipa_en' => isset($synData["ipa"][0]) ? addslashes($synData["ipa"][0]) : '',
            'ipa_us' => isset($synData["ipa"][1]) ? addslashes($synData["ipa"][1]) : '',
            'trans' => $trans_str,
            'update_time' => time(),
        ];

        print_r($data);

        $db = Yii::$app->db;

        $id = intval($db->createCommand("SELECT `id` FROM {{%english}} WHERE BINARY word='".$word."'")->queryScalar());

        if($id > 0){
            $line = $db->createCommand()->update('{{%english}}', $data, 'id='.$id)->execute();
            if($line == 1){
                exit(json_encode(["code"=>1, "info"=>"编辑成功"], JSON_UNESCAPED_UNICODE));
            }else{
                exit(json_encode(["code"=>-3, "info"=>"编辑失败"], JSON_UNESCAPED_UNICODE));
            }
        }else{
            exit;
            $line = $db->createCommand()->insert('{{%english}}', $data)->execute();
            if($line == 1){
                $id = $db->getLastInsertID();
                exit(json_encode(["code"=>1, "info"=>"添加成功", "id"=>$id], JSON_UNESCAPED_UNICODE));
            }else{
                exit(json_encode(["code"=>-3, "info"=>"添加失败"], JSON_UNESCAPED_UNICODE));
            }
        }
    }

    /**
     * 匹配人名
     */
    public static function matchName($text){
        $pattern = '/n\..*人名/';
        return preg_match($pattern, $text);
    }



    /**
     * 把翻译数组转换为字符串，同时过滤掉人名里的英文，以防止作为问题时提醒回答
     * @param $trans_arr
     * @return string
     */
    public static function getTransStr($trans_arr){
        $trans_str = '';
        foreach($trans_arr as $tran){
            $temp = self::matchName($tran) ? "n. 人名" : $tran;//过滤人名提示


            $temp = preg_replace_callback('/（.*?）/', function($matches){
                return preg_replace('/[a-zA-Z]/', '*', $matches[0]);
            }, $temp);

            $temp = preg_replace_callback('/\(.*?\)/', function($matches){
                return preg_replace('/[a-zA-Z]/', '*', $matches[0]);
            }, $temp);

            $temp = preg_replace_callback('/\[.*?\]/', function($matches){
                return preg_replace('/[a-zA-Z]/', '*', $matches[0]);
            }, $temp);

            $trans_str .= " ".$temp;
        }
        return trim($trans_str);
    }

    /**
     * 得到词库中破冰数量
     */
    public static function getIcebreakingWordCount(){
        $db = Yii::$app->db;
        $sql = "SELECT COUNT(*) FROM {{%english}} AS w WHERE w.correct_write>0";
        return $db->createCommand($sql)->queryScalar();//破冰单词量
    }

    /**
     * 得到词库中毕业单词数量
     */
    public static function getGraduatedWordCount(){
        $db = Yii::$app->db;
        $sql = "SELECT COUNT(*) FROM {{%english}} AS w WHERE w.correct_write>15";
        return $db->createCommand($sql)->queryScalar();//破冰单词量
    }

}
